﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YSC_Core.BLL.Domain.BackstageModels;
using YSC_Core.BLL.Domain.CommonModels;
using YSC_Core.BLL.Domain.Entity;
using YSC_Core.BLL.Domain.Models;
using YSC_Core.BLL.Domain.Utils;
using YSC_Core.BLL.Domain.ViewModels;
using YSC_Core.BLL.Repository;
using YSC_OpenPlatform_API.Entity;
using YSC_Services.BLL.Services.Interfaces;

namespace YSC_Services.BLL.Services.Implementations
{
    /// <summary>
    /// 后台用户接口是现实
    /// </summary>
    public class UserBackstageServices : IUserBackstageServices
    {
        private IEfRepository _rep;

        public UserBackstageServices(IEfRepository rep)
        {
            this._rep = rep;
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="status">是否停用: -1 停用0: 正常 1: 认证用户 2:未认证</param>
        /// <param name="sasearch"></param>
        /// <param name="isAttest">认证类型 0 市场 1 :产地 </param>
        /// <returns></returns>
        public PaginationModel GetUserAll(int index, int size, int status, string isAttest, string areCode, string sasearch)
        {
            //权限数据
            var sql1 = string.Empty;
            string[] arrt4 = null;
            if (!string.IsNullOrEmpty(areCode) && areCode != "undefined" && areCode != "null")
            {
                sql1 = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE YUnCode={0} UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                var areaAll = _rep.SqlQuery<Area>(sql1, areCode).ToList();

                arrt4 = areaAll.Select(p => p.YunCode).ToArray();
            }

            var roleList = _rep.Where<UserRole>(p => p.Status == 0).Select(p => p.UserId).ToArray();

            var yscUserAll = from a in _rep.Where<YscUser>(p => true)
                             where !string.IsNullOrEmpty(areCode) ? !roleList.Contains(a.Id) : a.Status == 0
                             join d in _rep.Where<Dictionary>(p => p.Status == 0) on a.AttestType equals d.Id into d
                             from di in d.DefaultIfEmpty()
                             join r in _rep.Where<Area>(p => p.Status == 0) on a.AreaUnCode equals r.YunCode into r
                             from ri in r.DefaultIfEmpty()
                             where !string.IsNullOrEmpty(areCode) && areCode != "undefined" && areCode != "null" ? arrt4.Contains(ri.YunCode) : ri.Status == 0
                             select new
                             {
                                 a.Id,
                                 UserName = System.Web.HttpUtility.UrlDecode(a.UserName, System.Text.Encoding.UTF8),
                                 a.Phone,
                                 a.Sex,
                                 a.Age,
                                 a.AreaUnCode,
                                 ri.AreaName,
                                 a.IsAttest,
                                 a.AttestType,
                                 AttestName = di.Name,
                                 a.Remarks,
                                 a.Status,
                                 a.OpenId,
                                 a.CreateTime
                             };

            var yscUserList = yscUserAll.OrderByDescending(p => p.CreateTime)
                         .WhereIf(p => p.UserName.Contains(sasearch) || p.Phone.Contains(sasearch) || p.AttestName.Contains(sasearch), string.IsNullOrEmpty(sasearch) == false)
                         .Where(p => status == 1 ? p.IsAttest == true : status == 2 ? p.IsAttest == false : p.Status == status)
                         .WhereIf(p => isAttest == "0" ? p.AttestName.Contains("市场") : isAttest == "1" ? p.AttestName.Contains("产地") : p.Status == 0, string.IsNullOrEmpty(isAttest) == false);


            var total = yscUserList.ToList().Count();

            var models = yscUserList
             .ToPaginationList(index, size)
                     .ToList();

            return new PaginationModel { Code = 200, Msg = "success", Total = total, Result = new { Data = models } };
        }

        /// <summary>
        /// 后台用户列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="status">是否停用: -1 停用0: 正常 1: 已授权 2:未授权</param>
        /// <param name="isAttest">认证类型 0 市场 1 :产地</param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public PaginationModel GetUserBackstageAll(int index, int size, int status, string isAttest, string areCode, string sasearch)
        {
            //权限数据
            var sql1 = string.Empty;
            string[] arrt4 = null;
            if (!string.IsNullOrEmpty(areCode) && areCode != "undefined" && areCode != "null")
            {
                sql1 = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE YUnCode={0} UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                var areaAll = _rep.SqlQuery<Area>(sql1, areCode).ToList();

                arrt4 = areaAll.Select(p => p.YunCode).ToArray();
            }


            var userAll = from a in _rep.Where<YscUser>(p => p.Status == 0)
                          join d in _rep.Where<Dictionary>(p => p.Status == 0) on a.AttestType equals d.Id into d
                          from di in d.DefaultIfEmpty()
                          join r in _rep.Where<UserRole>(p => p.Status == 0) on a.Id equals r.UserId
                          join e in _rep.Where<Area>(p => p.Status == 0) on r.RoleAreCode equals e.YunCode into e
                          from ei in e.DefaultIfEmpty()
                          select new
                          {
                              a.Id,
                              UserName = System.Web.HttpUtility.UrlDecode(a.UserName, System.Text.Encoding.UTF8),
                              a.Phone,
                              a.Sex,
                              a.Age,
                              a.AreaUnCode,
                              ei.AreaName,
                              a.IsAttest,
                              a.AttestType,
                              AttestName = di.Name,
                              ei.YunCode,
                              a.Remarks,
                              a.Status,
                              a.OpenId,
                              a.CreateTime
                          };

            var UserList = userAll.OrderByDescending(p => p.CreateTime)
                         // .Where(p => !string.IsNullOrEmpty(areCode) && areCode != "undefined" && areCode != "null" ? arrt4.Contains(p.YunCode) : p.Status == 0)
                         .WhereIf(p => arrt4.Contains(p.YunCode), string.IsNullOrEmpty(areCode) || areCode == "undefined" || areCode == "null" == false)
                         .WhereIf(p => p.UserName.Contains(sasearch) || p.Phone.Contains(sasearch) || p.AttestName.Contains(sasearch), string.IsNullOrEmpty(sasearch) == false)
                         .Where(p => status == 1 ? p.IsAttest == true : status == 2 ? p.IsAttest == false : p.Status == status)
                         .WhereIf(p => isAttest == "0" ? p.AttestName.Contains("市场") : isAttest == "1" ? p.AttestName.Contains("产地") : p.Status == 0, string.IsNullOrEmpty(isAttest) == false);


            var total = UserList.ToList().Count();

            var models = UserList
             .ToPaginationList(index, size)
                     .ToList();

            return new PaginationModel { Code = 200, Msg = "success", Total = total, Result = new { Data = models } };
        }

        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ReturnValueModel GetUser(string userId)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", "主键") };

            var itemAll = _rep.Where<YscUser>(p => p.Id == userId).ToList();
            if (itemAll.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到数据!" };

            var item = itemAll.FirstOrDefault();

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Data = item } };
        }

        /// <summary>
        /// 用户新增修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateUser(UserModels model)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 后台用户新增修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateBackstageUser(UserModels model)
        {

            List<string> mgsList = new List<string>();
            mgsList.Add((string.IsNullOrEmpty(model.UserName) ? "用户名" : null));
            mgsList.Add((string.IsNullOrEmpty(model.Password) ? "密码" : null));
            mgsList.Add((string.IsNullOrEmpty(model.Phone) ? "账户" : null));
            mgsList.Add((string.IsNullOrEmpty(model.AreaUnCode) ? "所属地区" : null));
            foreach (var item in mgsList)
                if (!string.IsNullOrEmpty(item))
                    return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", item) };

            if (string.IsNullOrEmpty(model.Id))
            {
                //新增
                if (_rep.Where<YscUser>(p => p.Phone == model.Phone).ToList().Count() > 0)
                    return new ReturnValueModel { Code = 400, Msg = "账户已被使用,请更改！" };

                YscUser yscUser = new YscUser()
                {
                    Id = Guid.NewGuid().ToString(),
                    UserName = model.UserName,
                    Password = UtilsHelp.GetMD5(model.Password),
                    Phone = model.Phone,
                    Sex = model.Sex,
                    Age = model.Age,
                    AreaUnCode = model.AreaUnCode,
                    HeadPortraitUrl = model.HeadPortraitUrl,
                    Background = model.Background,
                    IsAttest = model.IsAttest,
                    AttestType = model.AttestType,
                    Remarks = model.Remarks,
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = model.CreateId,
                    Introduce = model.Introduce
                };

                _rep.Insert(yscUser);
                return new ReturnValueModel { Code = 200, Msg = "success" };
            }
            else
            {
                //修改
                var yscUserAll = _rep.Where<YscUser>(p => p.Status == 0 && p.Id == model.Id).ToList();
                if (yscUserAll.Count() == 0)
                    return new ReturnValueModel { Code = 404, Msg = "查找不到该用户,请确认用户是否为可用状态!" };

                var yscUserItme = yscUserAll.FirstOrDefault();

                yscUserItme.UserName = string.IsNullOrEmpty(model.UserName) ? yscUserItme.UserName : model.UserName;
                yscUserItme.AreaUnCode = string.IsNullOrEmpty(model.AreaUnCode) ? yscUserItme.AreaUnCode : model.AreaUnCode;
                yscUserItme.Sex = model.Sex;
                yscUserItme.Age = model.Age;
                yscUserItme.HeadPortraitUrl = string.IsNullOrEmpty(model.HeadPortraitUrl) ? yscUserItme.HeadPortraitUrl : model.HeadPortraitUrl;
                yscUserItme.Background = string.IsNullOrEmpty(model.Background) ? yscUserItme.Background : model.Background;
                yscUserItme.IsAttest = model.IsAttest;
                yscUserItme.AttestType = string.IsNullOrEmpty(model.AttestType) ? yscUserItme.AttestType : model.AttestType;
                yscUserItme.Remarks = string.IsNullOrEmpty(model.Remarks) ? yscUserItme.Remarks : model.Remarks;
                yscUserItme.Introduce = string.IsNullOrEmpty(model.Introduce) ? yscUserItme.Introduce : model.Introduce;

                _rep.Update(yscUserItme);
                return new ReturnValueModel { Code = 200, Msg = "success" };
            }
        }
        /// <summary>
        ///  用户停用
        /// </summary>
        /// <param name="userId">主键Id</param>
        /// <returns></returns>
        public ReturnValueModel DelectUser(string userId)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", "主键") };

            var itemAll = _rep.Where<YscUser>(p => p.Id == userId && p.Status == 0).ToList();
            if (itemAll.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到数据!" };

            var item = itemAll.FirstOrDefault();
            item.Status = -1;
            _rep.Update(item);
            return new ReturnValueModel { Code = 200, Msg = "success", Result = "Delect Data OK!" };
        }



        /// <summary>
        /// 账户密码登陆
        /// </summary>
        /// <param name="userName">手机号</param>
        /// <param name="passWord">密码</param>
        /// <returns></returns>
        public ReturnValueModel Login(string userName, string passWord)
        {

            try
            {
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(passWord))
                    return new ReturnValueModel { Code = 400, Msg = "账户密码输入错误!" };

                string TokenUrl = "http://yscoauth.cnfm.com.cn:8099/connect/token";
               // string TokenUrl = "http://localhost:5000/connect/token";
                string dateStr = string.Format("username={0}&password={1}&client_id=ro.client&client_secret=secret&grant_type=password", userName, passWord);
                Dictionary<string, string> postData = new Dictionary<string, string>();

                postData.Add("userName", userName);
                postData.Add("password", UtilsHelp.GetMD5(passWord));
                postData.Add("client_id", "ro.client");
                postData.Add("client_secret", "secret");
                postData.Add("grant_type", "password");

                // 自己实现的http请求
                string postStr = HttpUtils.DictoryToGetParam(postData);
                var repose = HttpUtils.HttpPostRequest(TokenUrl, postStr);
                if (repose.Contains("400"))
                    return new ReturnValueModel { Code = 400, Msg = "请求错误!", Result = repose };

                var userItem = _rep.FirstOrDefault<YscUser>(p => p.Phone == userName && p.Password == UtilsHelp.GetMD5(passWord));
                var userRoleAll = _rep.Where<UserRole>(p => p.Status == 0 && p.UserId == userItem.Id).ToList();
                if (userRoleAll.Count() == 0)
                    return new ReturnValueModel { Code = 401, Msg = "权限不足，请联系管理员!" };


                TokenModel tokenModel = JsonConvert.DeserializeObject<TokenModel>(repose);
                tokenModel.UserName = System.Web.HttpUtility.UrlDecode(userItem.UserName, System.Text.Encoding.UTF8);
                tokenModel.RoleId = userRoleAll.FirstOrDefault().RoleId;
                tokenModel.RoleArea = userRoleAll.FirstOrDefault().RoleAreCode;
                tokenModel.HeadPortraitUrl = userItem.HeadPortraitImageUrl;
                tokenModel.UserId = userItem.Id;

                return new ReturnValueModel { Code = 200, Msg = "success!", Result = tokenModel };
            }
            catch (Exception e)
            {
                return new ReturnValueModel { Code = 500, Msg = "授权出现错误!", Result = e };

            }

        }

        /// <summary>
        /// 用户认证列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public ReturnValueModel UserAttestAll(int index, int size, string sasearch)
        {

            var userAttestAll = from a in _rep.Where<UserAttest>(p => p.Status == 0)
                                join u in _rep.Where<YscUser>(p => p.Status == 0) on a.UserId equals u.Id
                                join d in _rep.Where<Dictionary>(p => p.Status == 0) on a.AttestType equals d.Name
                                join i in _rep.Where<MediaImage>(p => p.Status == 0) on a.Id equals i.BllId
                                select new
                                {
                                    a.Id,
                                    UserName = System.Web.HttpUtility.UrlDecode(u.UserName, System.Text.Encoding.UTF8),
                                    d.Name,
                                    a.ContactsName,
                                    a.ContactsPhone,
                                    Url = string.Format("https://fishopeni.cnfm.com.cn:8095" + i.FileUrl),
                                    a.Remarks,
                                    a.CreateTime,
                                };

            var userAttestList = userAttestAll.OrderByDescending(p => p.CreateTime)
                        .WhereIf(p => p.UserName.Contains(sasearch) || p.Name.Contains(sasearch) || p.ContactsName.Contains(sasearch) || p.ContactsPhone.Contains(sasearch), string.IsNullOrEmpty(sasearch) == false);

            var total = userAttestAll.ToList().Count();

            var models = userAttestList
             .ToPaginationList(index, size)
                     .ToList();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = models } };
        }

        /// <summary>
        /// 用户认证市场列表
        /// </summary>
        /// <param name="userAttestId"></param>
        /// <returns></returns>
        public ReturnValueModel UserAttestUnitAll(int index, int size, string userAttestId)
        {
            var userAttestUnitAll = from a in _rep.Where<UserAttestUnit>(p => p.UserAttestId == userAttestId)
                                    join r in _rep.Where<Area>(p => p.Status == 0) on a.UnCode equals r.YunCode
                                    select new
                                    {
                                        a.UnitName,
                                        a.Address,
                                        a.CreateTime,
                                        a.Remarks,
                                        r.AreaName
                                    };

            var total = userAttestUnitAll.ToList().Count();

            var models = userAttestUnitAll
             .ToPaginationList(index, size)
                     .ToList();
            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = models } };
        }

        /// <summary>
        /// 用户认证审核
        /// </summary>
        /// <param name="userAttestId"></param>
        /// <param name="Remarks"></param>
        ///  <param name="isAttest">0:通过认证 1;否决</param>
        /// <returns></returns>
        public ReturnValueModel UserIsAttest(string userAttestId, string Remarks, int isAttest)
        {
            var UserAttestAll = _rep.Where<UserAttest>(p => p.Status == 0).ToList();
            if (UserAttestAll.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到认证信息!" };

            var userid = UserAttestAll.FirstOrDefault().UserId;
            var userAll = _rep.FirstOrDefault<YscUser>(p => p.Status == 0 && p.Id == userid);
            if (userAll.IsAttest == true)
                return new ReturnValueModel { Code = 423, Msg = "用户已经认证!" };

            var userImagerAll = _rep.Where<MediaImage>(p => p.Status == 0 && p.BllId == userAttestId).ToList();


            //更新数据
            if (isAttest == 1)
                AttesStatus(UserAttestAll, userImagerAll, Remarks);

            //  审核通过
            var UserAttest = UserAttestAll.FirstOrDefault();
            var dictionaryAll = _rep.Where<Dictionary>(p => p.Status == 0 && p.Type == "认证类型").ToList();

            //市场同步
            var UserUnitAll = _rep.Where<UserAttestUnit>(p => p.Status == 0).ToList();

            List<UserUnit> UserUnitList = new List<UserUnit>();
            List<string> unitList = new List<string>();

            //市场认证
            if (UserAttest.AttestType.Contains("市场"))
            {
                List<MarketUnit> marketUnitList = new List<MarketUnit>();
                var marketUnitAll = _rep.Where<MarketUnit>(p => p.Status == 0).ToList();
                foreach (var item in UserUnitAll)
                {
                    //判断系统是否具有市场
                    if (marketUnitAll.Where(p => p.MarketName == item.UnitName).Count() > 0)
                    {
                        unitList.Add(marketUnitAll.Where(p => p.MarketName == item.UnitName).FirstOrDefault().Id);
                        continue;
                    }
                    //添加新市场
                    MarketUnit marketUnit = new MarketUnit()
                    {
                        Id = Guid.NewGuid().ToString(),
                        MarketName = item.UnitName,
                        Address = item.Address,
                        UnCode = UtilsHelp.GetRandNumInt().ToString(),
                        AreaUnCode = item.UnCode,
                        Status = 1,
                        CreateTime = DateTime.Now,
                        CreateId = UserAttest.UserId,
                        ContactsName = UserAttest.ContactsName,
                        ContactsPhone = UserAttest.ContactsPhone
                    };
                    //添加用户市场关系
                    UserUnit userUnit = new UserUnit()
                    {
                        Id = Guid.NewGuid().ToString(),
                        UserId = UserAttest.UserId,
                        UnitId = marketUnit.Id,
                        UnitType = dictionaryAll.Where(p => p.Name == UserAttest.AttestType).FirstOrDefault().Id,
                        Status = 0,
                        CreateTime = DateTime.Now,
                        CreateId = UserAttest.UserId
                    };

                    UserUnitList.Add(userUnit);
                    marketUnitList.Add(marketUnit);
                }

                if (marketUnitList.Count() == 0 && unitList.Count() == 0)
                    return new ReturnValueModel { Code = 400, Msg = "用户市场信息有误!" };

                if (marketUnitList.Count() > 0)
                {
                    //保存市场
                    _rep.InsertList(marketUnitList);
                    _rep.InsertList(UserUnitList);
                }

                if (unitList.Count() > 0)
                {
                    UserUnitList.Clear();
                    foreach (var item in unitList)
                    {
                        UserUnit userUnit = new UserUnit()
                        {
                            Id = Guid.NewGuid().ToString(),
                            UserId = UserAttest.UserId,
                            UnitId = item,
                            UnitType = dictionaryAll.Where(p => p.Type == UserAttest.AttestType).FirstOrDefault().Id,
                            Status = 0,
                            CreateTime = DateTime.Now,
                            CreateId = UserAttest.UserId
                        };
                        UserUnitList.Add(userUnit);
                    }
                    _rep.InsertList(UserUnitList);
                }

                //用户信息更改
                userAll.IsAttest = true;
                userAll.AttestType = dictionaryAll.Where(p => p.Name == UserAttest.AttestType).FirstOrDefault().Id;
                _rep.Update(userAll);
                //媒体信息更改
                AttesStatus(UserAttestAll, userImagerAll, Remarks, 1);
                return new ReturnValueModel { Code = 200, Msg = "认证成功!" };
            }

            List<PlaceOfOriginUnit> placeOfOriginUnitList = new List<PlaceOfOriginUnit>();
            var placeOfOriginUnitAll = _rep.Where<PlaceOfOriginUnit>(p => p.Status == 0).ToList();
            foreach (var item in UserUnitAll)
            {
                //判断系统是否具有产地
                if (placeOfOriginUnitAll.Where(p => p.PlaceOriginName == item.UnitName).Count() > 0)
                {
                    unitList.Add(placeOfOriginUnitAll.Where(p => p.PlaceOriginName == item.UnitName).FirstOrDefault().Id);
                    continue;
                }
                //添加新产地
                PlaceOfOriginUnit marketUnit = new PlaceOfOriginUnit()
                {
                    Id = Guid.NewGuid().ToString(),
                    PlaceOriginName = item.UnitName,
                    Address = item.Address,
                    UnCode = UtilsHelp.GetRandNumInt().ToString(),
                    AreaUnCode = item.UnCode,
                    Status = 1,
                    CreateTime = DateTime.Now,
                    CreateId = UserAttest.UserId,
                    ContactsName = UserAttest.ContactsName,
                    ContactsPhone = UserAttest.ContactsPhone
                };
                //添加用户市场关系
                UserUnit userUnit = new UserUnit()
                {
                    Id = Guid.NewGuid().ToString(),
                    UserId = UserAttest.UserId,
                    UnitId = marketUnit.Id,
                    UnitType = dictionaryAll.Where(p => p.Type == UserAttest.AttestType).FirstOrDefault().Id,
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = UserAttest.UserId
                };

                UserUnitList.Add(userUnit);
                placeOfOriginUnitList.Add(marketUnit);
            }

            if (placeOfOriginUnitList.Count() == 0 && unitList.Count() == 0)
                return new ReturnValueModel { Code = 400, Msg = "用户市场信息有误!" };

            if (placeOfOriginUnitList.Count() > 0)
            {
                //保存市场
                _rep.InsertList(placeOfOriginUnitList);
                _rep.InsertList(UserUnitList);
            }

            if (unitList.Count() > 0)
            {
                UserUnitList.Clear();
                foreach (var item in unitList)
                {
                    UserUnit userUnit = new UserUnit()
                    {
                        Id = Guid.NewGuid().ToString(),
                        UserId = UserAttest.UserId,
                        UnitId = item,
                        UnitType = dictionaryAll.Where(p => p.Type == UserAttest.AttestType).FirstOrDefault().Id,
                        Status = 0,
                        CreateTime = DateTime.Now,
                        CreateId = UserAttest.UserId
                    };
                    UserUnitList.Add(userUnit);
                }
                _rep.InsertList(UserUnitList);
            }

            //用户信息更改
            userAll.IsAttest = true;
            userAll.AttestType = dictionaryAll.Where(p => p.Type == UserAttest.AttestType).FirstOrDefault().Id;
            _rep.Update(userAll);
            //媒体信息更改
            AttesStatus(UserAttestAll, userImagerAll, Remarks, 1);
            return new ReturnValueModel { Code = 200, Msg = "认证成功!" };
        }

        public void AttesStatus(List<UserAttest> userAttestAll, List<MediaImage> userImagerAll, string Remarks, int isAttest = -1)
        {
            foreach (var items in userAttestAll)
            {
                items.Status = isAttest;
                items.Remarks = Remarks;

                foreach (var attesItems in items.UserAttestUnitAll)
                    attesItems.Status = isAttest;
                _rep.Update(items);
            }

            foreach (var items in userImagerAll)
                items.Status = isAttest;

            _rep.UpdateList(userImagerAll);
        }


        /// <summary>
        ///  角色菜单列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public PaginationyMenuModel GetRoleMenu(string roleid)
        {

            if (string.IsNullOrEmpty(roleid))
                return null;

            var checkedIdList = from a in _rep.Where<RoleMenu>(p => p.RoleId == roleid)
                                join m in _rep.Where<Menu>(p => true) on a.MenuId equals m.Id
                                select new
                                {
                                    id = m.Id,
                                    name = m.MenuName,
                                    pid = m.SuperionMenuId.Trim()
                                };
            List<string> checkedId = new List<string>();
            foreach (var item in checkedIdList.ToList())
                checkedId.Add(item.id);
            var MenuList = _rep.Where<Menu>(p => true).Select(p => new { p.Id, p.MenuName, p.SuperionMenuId }).ToList();

            List<MenuTreeModel> list = new List<MenuTreeModel>();
            foreach (var parentNodeList in MenuList)
            {
                MenuTreeModel menuNode = new MenuTreeModel();
                menuNode.id = parentNodeList.Id;
                menuNode.name = parentNodeList.MenuName;
                menuNode.pid = parentNodeList.SuperionMenuId;
                list.Add(menuNode);
            }
            return new PaginationyMenuModel { code = 0, msg = "success", data = new { list, checkedId } };
        }

        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public PaginationModel GetRoleAll(int index, int size, string sasearch)
        {
            var roleAll = from a in _rep.Where<Role>(p => p.Status == 0)
                          join d in _rep.Where<Dictionary>(p => p.Status == 0) on a.RoleType equals d.Id
                          join di in _rep.Where<Dictionary>(p => p.Status == 0) on a.PlatformId equals di.Id
                          select new
                          {
                              a.Id,
                              a.RoleName,
                              RoleType = d.Name,
                              PlatformId = di.Name,
                              a.Remarks,
                              a.CreateTime
                          };

            var roleList = roleAll
                .OrderByDescending(p => p.CreateTime)
                .WhereIf(p => p.RoleName.Contains(sasearch), string.IsNullOrEmpty(sasearch) == false);

            var models = roleList
                  .ToPaginationList(index, size)
                     .ToList();

            return new PaginationModel { Code = 200, Msg = "success!", Result = new { Data = models } };
        }

        /// <summary>
        /// 角色菜单赋值
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateRoleMenu(UpdateRoleMenu model)
        {
            if (string.IsNullOrEmpty(model.RoleId))
                return new ReturnValueModel { Code = 400, Msg = "角色Id不能为空!" };

            var menuAll = _rep.Where<RoleMenu>(p => p.Status == 0 && p.RoleId == model.RoleId).ToList();
            if (menuAll.Count() > 0)
                _rep.RemoveRange(menuAll);

            List<RoleMenu> roleList = new List<RoleMenu>();
            foreach (var itme in model.ListMenuId)
            {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.Id = Guid.NewGuid().ToString();
                roleMenu.RoleId = model.RoleId;
                roleMenu.MenuId = itme;
                roleMenu.CreateTime = DateTime.Now;
                roleMenu.Status = 0;
                roleMenu.CreateId = "4076e59b-c219-11e9-a7b7-48d53943449f";

                roleList.Add(roleMenu);
            }
            if (roleList.Count() > 0)
                _rep.InsertList(roleList);

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 用户角色授予
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleId"></param>
        /// <param name="roleAreCode">省市用户编码Core</param>
        /// <returns></returns>
        public ReturnValueModel AddUserRole(string userId, string roleId, string roleAreCode, string remarks)
        {
            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(roleId))
                return new ReturnValueModel { Code = 400, Msg = "用户参数提交错误!" };


            var userRoleAll = _rep.Where<UserRole>(p => p.Status == 0 && p.UserId == userId).ToList();
            if (userRoleAll.Count() > 0)
                _rep.RemoveRange(userRoleAll);

            var RoleAll = _rep.Where<Role>(p => p.Status == 0 && p.Id == roleId).ToList().FirstOrDefault();
            if (RoleAll.RoleName != "省级用户" && RoleAll.RoleName != "市级用户")
                roleAreCode = string.Empty;

            UserRole model = new UserRole()
            {
                Id = Guid.NewGuid().ToString(),
                UserId = userId,
                RoleId = roleId,
                Remarks = remarks,
                RoleAreCode = roleAreCode,
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = "4076e59b-c219-11e9-a7b7-48d53943449f"
            };

            _rep.Insert(model);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 用户菜单
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public ReturnValueModel UserMenu(string roleId)
        {
            var userMenu = from a in _rep.Where<Role>(p => p.Status == 0 && p.Id == roleId)
                           join r in _rep.Where<RoleMenu>(p => p.Status == 0) on a.Id equals r.RoleId
                           join m in _rep.Where<Menu>(p => p.Status == 0) on r.MenuId equals m.Id
                           select new
                           {
                               m.MuCode
                           };

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = userMenu.ToList() } };
        }

        /// <summary>
        /// 用户密码修改
        /// </summary>
        /// <param name="password"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnValueModel GetUserPasswordChange(string oldPassword, string password, string id)
        {
            if (string.IsNullOrEmpty(password))
                return new ReturnValueModel { Code = 400, Msg = "请输入密码!" };
            var userAll = _rep.Where<YscUser>(p => p.Id == id).ToList();
            if (userAll.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "用户状态异常!" };

            var userItem = userAll.FirstOrDefault();

            if (userItem.Password != UtilsHelp.GetMD5(oldPassword))
                return new ReturnValueModel { Code = 400, Msg = "原密码错误!" };

            userItem.Password = UtilsHelp.GetMD5(password);
            _rep.Update(userItem);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <returns></returns>
        public PaginationyMenuModel GetMenuAll()
        {
            var MenuList = _rep.Where<Menu>(p => true).Select(p => new { p.Id, p.MenuName, p.SuperionMenuId }).ToList();

            List<MenuTreeModel> list = new List<MenuTreeModel>();
            foreach (var parentNodeList in MenuList)
            {
                MenuTreeModel menuNode = new MenuTreeModel();
                menuNode.id = parentNodeList.Id;
                menuNode.name = parentNodeList.MenuName;
                menuNode.pid = parentNodeList.SuperionMenuId;
                list.Add(menuNode);
            }
            return new PaginationyMenuModel { code = 0, msg = "success", data = new { list } };
        }

        /// <summary>
        /// 菜单新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddMenu(MenuModel model)
        {
            if (string.IsNullOrEmpty(model.MenuName) && string.IsNullOrEmpty(model.MuCode))
                return new ReturnValueModel { Code = 400, Msg = "请填写菜单名称、编码！" };

            var menuAll = _rep.Where<Menu>(p => p.Status == 0).ToList();

            if (menuAll.Where(p => p.MenuName == model.MenuName).Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "菜单名称已存在！" };

            if (menuAll.Where(p => p.MuCode == model.MuCode).Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "菜单编码已存在！" };

            Menu menu = new Menu()
            {
                Id = Guid.NewGuid().ToString(),
                SuperionMenuId = model.SuperionMenuId,
                MenuName = model.MenuName,
                Sql = model.SuperionMenuId == "0" ? 1 : 2,
                Remarks = model.Remarks,
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = "4076e59b-c219-11e9-a7b7-48d53943449f",
                MuCode = model.MuCode
            };

            _rep.Insert(menu);
            return new ReturnValueModel { Code = 200, Msg = "success" };
        }

        /// <summary>
        /// 一级菜单
        /// </summary>
        /// <returns></returns>
        public ReturnValueModel TopMenu()
        {
            var meunTopAll = _rep.Where<Menu>(p => p.Status == 0 && p.Sql == 1)
                .Select(p => new { p.Id, p.MenuName }).ToList();

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Data = meunTopAll } };
        }

    }
}
